package com.itheima.advance.xml.parse;

import com.itheima.advance.xml.domain.Student;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class StudentXmlParse {

    public static final String STUDENTS_XML_PATH = "itheima-advace-xml\\xml\\students.xml";
    public static void main(String[] args) {

        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new FileInputStream(STUDENTS_XML_PATH));
            Element rootElement = document.getRootElement();
            List<Element> studentElements = rootElement.elements("student");
            ArrayList<Student> arrayList = new ArrayList<>();
            for (Element element : studentElements){
                Attribute idAttribute = element.attribute("id");
                String id = idAttribute.getValue();
                Element nameElement = element.element("name");
                String name = nameElement.getText();
                Element ageElement = element.element("age");
                String age = ageElement.getText();
                Element addressElement = element.element("address");
                String address = addressElement.getText();
                Student student = new Student();
                student.setStuId(id);
                student.setStuName(name);
                student.setStuAge(age);
                student.setStuAddress(address);
                arrayList.add(student);
            }
            arrayList.forEach(s -> System.out.println(s));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
